package com.yneusoft.common.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * @author lt
 * @date 2021/10/21 14:09
 * @description: JWT生成、校验、获取payload --工具类
 */
public class JwtTool {
    private static String TOKEN = "token!Q@W3e4r";
    /**
     * 生成token
     * @param aid //传入用户aid
     * @return 返回token
     */
    public static String getToken(Integer aid){
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("aid",aid);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,72);
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }

    /**
     * 验证token
     * @param token JWT
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    /**
     * 获取token中payload
     * @param token JWT
     * @return payload
     */
    public static DecodedJWT getToken(String token){
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
}
